<template>
	<div>
		<el-tabs type="border-card" v-model="regionGrade"  @tab-click="handleTabsClick">
			<el-tab-pane label="行政区（区）" :name="3" v-if="!userInfo.authArea"></el-tab-pane>
			<el-tab-pane label="行政区（街道）" :name="4"></el-tab-pane>

			<template v-if="regionGrade == 3 || userInfo.authArea">
				<el-checkbox-group v-model="checkList" @change="handleChange">
					<el-checkbox v-for="item in treeData" :key="item.administrationName" :label="item.administrationName" :value="item.administrationName" />
				</el-checkbox-group>
			</template>
			<template v-if="regionGrade == 4 && !userInfo.authArea">
				<el-tabs  v-model="activeAreaName" class="demo-tabs">
					<el-tab-pane v-for="item in treeData" :key="item.id" :name="item.administrationName">
						<template v-slot:label>
							<el-badge :value="getBrageNum(item)" :show-zero="false" type="success" style="--el-index-normal:1000">
								<span>{{ item.administrationName }}</span>
							</el-badge>
						</template>
					</el-tab-pane>
					<el-checkbox-group v-model="checkList" @change="handleChange">
						<el-checkbox
							v-for="item in streetList"
							:key="item.administrationName"
							:label="item.administrationName"
							:value="item.administrationName"
						/>
					</el-checkbox-group>
				</el-tabs>
			</template>
		</el-tabs>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod/index'
import { useCrudStore } from '@/stores/crud'
const { areaTreeData, setMenuTreeData } = useCrudStore()
import {getStore} from '@/utils/store'

const emit = defineEmits(['update:modelValue'])
const userInfo = getStore('userInfo')||{}
const regionGrade = ref(userInfo.authArea?4:3)
const activeAreaName = ref('南京市')
const checkList = ref([])
const treeData = ref(areaTreeData)
const administrationPid =userInfo.authArea || userInfo.authCity || 199554

const streetList = computed(() => {
	const tempObj = treeData.value.find((item) => item.administrationName == activeAreaName.value) || {}
	return tempObj.children || []
})

const getBrageNum = (item) => {
	let count = 0
	item.children.map((item) => {
		if (checkList.value.includes(item.administrationName)) {
			count++
		}
	})
	return count
}

const handleTabsClick = ()=> {
  checkList.value = []
  handleChange()
}
const handleChange = () => {
	emit('update:modelValue', checkList.value)
}
const getInitData = () => {
	treeData.value = areaTreeData

	if (areaTreeData.length == 0) {
		apiMod
			.sysadministration_getTree({
				regionGrade: 5,
				administrationPid: administrationPid,
				isNotShowProvince: false,
			})
			.then((res) => {
				treeData.value = res.data
				setMenuTreeData(res.data)
			})
	}
}

onMounted(() => {
	getInitData()
})
</script>

<style scoped>
:deep(.el-badge__content.is-fixed) {
  top:6px;
}
</style>
